import os
import joblib
from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score, roc_auc_score
from src.train import PowerLoadModel, data_processing
from util.commonUtil import model_view_AUC, model_hunxiao


def model_predict(path, logger):
    try:
        # 1.加载数据和模型
        input_file = os.path.join(os.path.abspath('../data'), path)
        logger.info(f"加载预测数据: {input_file}")
        model = PowerLoadModel(input_file)

        # 2.数据预处理（使用训练时的scaler）
        x_test, y_test, _ = data_processing(model.data_source, logger)
        scaler_path = os.path.join(os.path.abspath('../model'), 'scaler.pkl')
        scaler = joblib.load(scaler_path)
        x_test = scaler.transform(x_test)  # 使用训练好的scaler
        logger.info(f"预测数据预处理完成，特征形状: {x_test.shape}")

        # 3.加载模型
        model_path = os.path.join(os.path.abspath('../model'), 'logistic_model.pkl')
        clf = joblib.load(model_path)
        logger.info(f"模型加载成功: {model_path}")

        # 4.预测与评估
        y_pre = clf.predict(x_test)
        y_pred_proba = clf.predict_proba(x_test)[:, 1]

        metrics = {
            '准确率': accuracy_score(y_test, y_pre),
            '精确率': precision_score(y_test, y_pre),
            '召回率': recall_score(y_test, y_pre),
            'F1分数': f1_score(y_test, y_pre),
            'AUC': roc_auc_score(y_test, y_pred_proba)
        }
        for name, value in metrics.items():
            logger.info(f"{name}: {value:.4f}")
            print(f'{name}: {value:.4f}')

        # 5.可视化
        model_view_AUC(x_test, y_test, clf)
        model_hunxiao(y_test, y_pre)

    except Exception as e:
        logger.error(f"预测过程失败: {str(e)}", exc_info=True)
        raise